package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;

import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.User;
import com.freely.data.managerUtils.FreelySharedPreferences;

import com.freely.ui.util.DataVerification;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.util.VerificationUtil;
import com.freely.ui.viewModel.DetailViewModel;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;

public class DetailEditActivity extends NavigationActivity {

    @BindView(R2.id.user_head_icon)
    ImageView useHeadIcon;
    @BindView(R.id.user_nick)
    TextInputEditText userNick;
    @BindView(R.id.user_phone)
    TextInputEditText userPhoto;
    @BindView(R.id.user_email)
    TextInputEditText userEmail;
    @BindView(R.id.user_nick_layout)
    TextInputLayout userNickLayout;
    @BindView(R.id.user_email_layout)
    TextInputLayout userEmailLayout;
    @BindView(R.id.user_phone_layout)
    TextInputLayout userPhoneLayout;

    private BottomSheetDialog dialog;
    private String headIconPath;
    private Bitmap headIconBitmap;
    private DetailViewModel detailViewModel;
    private static final String TAG = "DetailEditActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_edit);
        detailViewModel = new DetailViewModel(this);
        initDetailEdit();
    }

    @Override
    protected void onCreateToolbar(Toolbar toolbar, TextView title, ImageButton logo) {
        super.onCreateToolbar(toolbar, title, logo);
        toolbar.inflateMenu(R.menu.detail_edit);
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.finish:
                    if(!userPhoneLayout.isErrorEnabled() &&!userNickLayout.isErrorEnabled()
                            &&!userEmailLayout.isErrorEnabled()){
                        if(UpdateDetail()){
                            Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
            return false;
        });
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, DetailEditActivity.class);
        context.startActivity(intent);
    }
    public void initDetailEdit(){
        detailViewModel.loadUser();
        detailViewModel.getUser().observe(this,user -> {

            userNick.setText(user.getUserName());

            if (user.getUserPhone()!=null)
                userPhoto.setText(user.getUserPhone());

            userEmail.setText(user.getUserEmail());

            byte[] headIconByte = Base64.decode(user.getUserImage(), Base64.DEFAULT);
            Glide.with(this)
                    .load(headIconByte)
                    .apply(RequestOptions.circleCropTransform())
                    .into(useHeadIcon);
        });
    }
    @OnTextChanged(R.id.user_nick)
    void userNickTextChangedListener(Editable s){
        VerificationUtil.userNickVerificationHint(
                s.toString(),userNickLayout,
                getString(R.string.user_nick_length_error_hint)
        );
    }
    @OnTextChanged(R.id.user_phone)
    void userPhoneTextChangedListener(Editable s){
        VerificationUtil.userPhoneVerificationHint(
                s.toString(),userPhoneLayout,
                getString(R.string.user_phone_length_error_hint)
        );
    }

    @OnTextChanged(R.id.user_email)
    void userEmailTextChangedListener(Editable s){
        VerificationUtil.emailVerificationHint(
                s.toString(),userEmailLayout,
                getString(R.string.user_email_format_error_hint)
        );
    }
    @OnClick(R.id.user_head_icon)
    void selectHeadIcon(){
        if (dialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_photo_select, null);
            TextView capture = view.findViewById(R.id.capture);
            TextView gallery = view.findViewById(R.id.gallery);
            capture.setOnClickListener(this::groupHeadIconSelect);
            gallery.setOnClickListener(this::groupHeadIconSelect);
            dialog = new BottomSheetDialog(this);
            dialog.setContentView(view);
        }
        dialog.show();
    }

    void groupHeadIconSelect(View view) {
        switch (view.getId()) {
            case R.id.capture:
                //相机选取群头像
                PhotoSelectActivity.startActivity(
                        DetailEditActivity.this,
                        CreateGroupActivity.PHOTO_SELECT,
                        PhotoSelectActivity.CAPTURE
                );
                break;
            case R.id.gallery:
                //相册选取群头像
                PhotoSelectActivity.startActivity(
                        DetailEditActivity.this,
                        CreateGroupActivity.PHOTO_SELECT,
                        PhotoSelectActivity.GALLERY
                );
                break;
        }
        dialog.cancel();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case CreateGroupActivity.PHOTO_SELECT:
                Log.d("detail", "onActivityResult: 图片选择结果");
                if (resultCode != RESULT_OK) {
                    return;
                }
                Log.d("detail", "onActivityResult: 成功选择图片");
                headIconPath = data.getStringExtra(PhotoSelectActivity.RESULT);
                Log.d("detail", "onActivityResult: 判断图片路径");
                if (TextUtils.isEmpty(headIconPath)) {
                    return;
                }
                Log.d("detail", "onActivityResult: 图片路径正确");
                Glide.with(this)
                        .asBitmap()
                        .load(new File(headIconPath))
                        .apply(RequestOptions.circleCropTransform())
                        .listener(new RequestListener<Bitmap>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                                return false;
                            }
                            @Override
                            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                                headIconBitmap = resource;
                                return false;
                            }
                        })
                        .into(useHeadIcon);
                break;
        }
    }

    public boolean UpdateDetail(){
        boolean startUpdate = false;
        User user = detailViewModel.getUser().getValue();
        String userNick = this.userNick.getText().toString();
        String userPhone = this.userPhoto.getText().toString();
        String userEmail=this.userEmail.getText().toString();

        User updateUser = new User();
        updateUser.setUserId(user.getUserId());


        if(!user.getUserName().equals(userNick)){
            updateUser.setUserName(userNick);
            startUpdate = true;
        }
        if(userPhone.length() > 0 && !userPhone.equals(user.getUserPhone())){
            updateUser.setUserPhone(userPhone);
            startUpdate = true;
        }

        if(!user.getUserEmail().equals(userEmail)){
            updateUser.setUserEmail(userEmail);
            startUpdate = true;
        }

        if(headIconBitmap == null && !startUpdate){
            return false;
        }

        Disposable disposable = Single.just(updateUser)
                .subscribeOn(Schedulers.io())
                .subscribe(temp -> {
                    if(headIconBitmap != null){
                        //头像由bitmap转为base64
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        headIconBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                        byte[] headIconByte = outputStream.toByteArray();
                        updateUser.setUserImage( ByteString.of(headIconByte).base64());
                    }
                    //发送更新请求
                    detailViewModel.updateDetail(updateUser);
                }, throwable -> {
                    //头像错误
                    ErrorUtil.dataReadErrorHint("头像错误",throwable);
                });
        register(disposable);
        return true;
    }

    public DetailViewModel getDetailViewModel() {
        return detailViewModel;
    }
}
